<template>
  <div>
    <el-button type="success" @click="open" icon="el-icon-edit">添加</el-button>
    <el-dialog center :visible.sync="dialogFormVisible" fullscreen>
      
    </el-dialog>
<div ref="toastUIEditor"></div>
  </div>
</template>
<script>
import Editor from '@toast-ui/editor';
import 'codemirror/lib/codemirror.css'; // Editor's Dependency Style
import '@toast-ui/editor/dist/toastui-editor.css'; // Editor's Style
import "@toast-ui/editor/dist/i18n/zh-cn";
import { uploadFile, addPicture } from "@/api/picture";
export default {
  data() {
    return {
      dialogFormVisible: false,
      contentSortUid: "8c767391edb3ae78418fb43697857f9e", //头像相册分类得uid
    }
  },
  mounted() {
    const options = {
      el: this.$refs.toastUIEditor,
      previewStyle: 'vertical',
      height: '500px',
      initialEditType: 'markdown',
      language: "zh-CN",
      initialValue: 'Select some text and choose a color from the toolbar.',
    }
    this.editor = new Editor(options)
    // 删除默认监听事件
    this.editor.eventManager.removeEventHandler('addImageBlobHook')
    // 添加自定义监听事件
    this.editor.eventManager.listen('addImageBlobHook', (blob, callback) => {
      // 此处填写自己的上传逻辑，url为上传后的图片地址
      this.editorUploadPic(blob, url => {
        callback(url)
      })
    })
  },
  methods: {
    open() {
      this.dialogFormVisible = true
      this.$nextTick(function(){



})
      
    },
    /**
     * 编辑器中上传图片至服务器
     */
    editorUploadPic(file, callback) {
      // this.editor.toastuiEditor.invoke("getMarkdown");
      var formData = new FormData();
      formData.append("multipartFile", file);
      formData.append("userUid", this.$store.getters.userUid);
      formData.append("sortName", "admin");
      //上传图片file
      uploadFile(formData).then((response) => {
        let picture = {};
        picture.fileUid = response.data.uid;
        picture.pictureSortUid = this.contentSortUid;
        picture.picName = response.data.picName;
        //添加到分类中，添加到数据库
        addPicture(picture).then((resp) => {
          callback(response.data.picUrl)
          this.$notify({
            title: "成功",
            message: "上传成功！",
            type: "success",
          });

          //   this.form.avatarUrl = response.data.picUrl;
          //   this.form.avatar = response.data.uid;
          //   this.showCutter = false;
        });
      });




      //   const formData = new FormData()
      //   formData.append('file', file)
      //   const ajax = new XMLHttpRequest()
      //   ajax.open('POST', 'http://localhost:9100/qiniu/upload', true)
      //   ajax.send(formData)
      //   ajax.onreadystatechange = function() {
      //     if (ajax.readyState === 4) {
      //       if ((ajax.status >= 200 && ajax.status < 300) || ajax.status === 304) {
      //         console.log('上传成功')
      //         const obj = JSON.parse(ajax.responseText)
      //         callback(obj.result)
      //       }
      //     }
      //   }
    }
  }
}
</script>